package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.controller.utils.RedisIdWorker;
import com.hmdp.controller.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    private static final String SECKILL_VOUCHER_ORDER = "seckill_voucher:";
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("script/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    private static final String GROUP_NAME = "g1";
    private static final String CONSUMER_NAME  = "c1";
    private static final String QUEUE_NAME = "stream.orders";

    @PostConstruct
    private void init(){
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(QUEUE_NAME))){
            stringRedisTemplate.opsForStream().createGroup(QUEUE_NAME, ReadOffset.from("0"),GROUP_NAME);
            log.debug("Stream队列创建成功");
        }
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    public class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    // 获取消息队列中的订单信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from(GROUP_NAME, CONSUMER_NAME),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(QUEUE_NAME, ReadOffset.lastConsumed())
                    );
                    if (list == null || list.isEmpty()){
                        continue;
                    }
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.copyProperties(values,VoucherOrder.class);
                    // 如果获取成功，可以下单
                    handleVoucherOrder(voucherOrder);
                    // ACK确认 SACK stream.orders g1 id [id1 id2 id3 ...]
                    stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        }
    }
    private void handlePendingList() {
        while (true) {  // 不断获取消息队列中的订单信息
            try {
                // 获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from(GROUP_NAME, CONSUMER_NAME),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(QUEUE_NAME, ReadOffset.from("0"))
                );
                // 判断异常消息获取是否成功
                if (list == null || list.isEmpty()) {
                    // 如果获取失败，说明pending-list中没有异常消息，结束循环
                    break;
                }
                // 解析消息中的订单信息 MapRecord<消息id, 消息key，消息value>
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> values = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                // 如果获取成功，可以下单
                handleVoucherOrder(voucherOrder);
                // ACK确认 SACK stream.orders g1 id [id1 id2 id3 ...]
                stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, record.getId());
            } catch (Exception e) {
                log.error("处理订单异常", e);
                // 防止处理频繁，下次循环休眠20毫秒
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
    private IVoucherOrderService proxy;

    public void handleVoucherOrder(VoucherOrder voucherOrder){
        proxy.createVoucherOrder(voucherOrder);
    }

    /**
     * 秒杀下单优惠券
     * @param voucherId 优惠券id
     * @return 下单id
     */
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始！");// 判断秒杀是否开始
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束！");        // 判断秒杀是否结束
        }
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")        // 扣减库存
                .eq("voucher_id", voucherId)
                .eq("stock",seckillVoucher.getStock())// 乐观锁思想，保证库存前后一致性
                .update();
        if (!success) {
            // 扣减失败
            throw new RuntimeException("扣减失败，秒杀券扣减失败（库存不足）！");
        }
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nextId(SECKILL_VOUCHER_ORDER));  // 订单id
        Long userId = UserHolder.getUser().getId();
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);   // 代金券id
        success = this.save(voucherOrder);
        if (!success) {
            // 创建秒杀券订单失败
            throw new RuntimeException("创建秒杀券订单失败！");
        }
        // 判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
            return Result.fail("秒杀券已抢空！");
        }
        return createSecKillVoucherOrder(voucherId);
    }

    @Transactional
    public Result createSecKillVoucherOrder(Long voucherId) {
        // 判断是否是一人一单
        Long userId = UserHolder.getUser().getId();
        synchronized(userId.toString().intern()) {// intern()方法才能保证每个用户的锁对象唯一
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("该秒杀券用户已经购买过一次了！");
            }
            boolean success = seckillVoucherService.update()            // 扣减库存
                    .setSql("stock = stock - 1")    // set stoke = stoke - 1
                    .eq("voucher_id", voucherId).gt("stock", 0)	// where id = ? and stock > 0
                    .update();
            if (!success) {
                // 扣减失败
                throw new RuntimeException("扣减失败，秒杀券扣减失败（库存不足）！");
            }
            // 创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setId(redisIdWorker.nextId(SECKILL_VOUCHER_ORDER));  // 订单id
            voucherOrder.setUserId(userId);   // 用户id
            voucherOrder.setVoucherId(voucherId);   // 代金券id
            success = this.save(voucherOrder);
            if (!success) {
                // 创建秒杀券订单失败
                throw new RuntimeException("创建秒杀券订单失败！");
            }
            // 返回订单id
            return Result.ok(voucherOrder.getId());
        }
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        //5.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("扣减失败！");
        }
        //6.创建订单
        voucherOrderService.save(voucherOrder);
    }
}
